﻿
using MySql.Data.MySqlClient;
using System;
using System.Data;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
using System.Linq;

namespace RM.BasicLibrary.Models.Databases
{
    public class MYSQLDatabase : BaseDatabase, IDatabase
    {
        public override string ConnectionString { get; set; }
        protected override void CreateConnection()
        {
            DbConnectionIns = new MySqlConnection(ConnectionString);
            dbCommand = new MySqlCommand();
        }
        public override DataTable GetDataTable(string cmdText, CommandType type = CommandType.Text, params DbParameter[] parm)
        {
            DataTable dt = new DataTable();
            using (MySqlDataAdapter adapter = new MySqlDataAdapter(cmdText, ConnectionString))
            {
                adapter.SelectCommand.CommandType = type;
                adapter.SelectCommand.Parameters.AddRange(parm);
                adapter.Fill(dt);
                return dt;
            }
        }
        public override DbContext CreateDbContext(string connectionString = null)
        {
            this.ConnectionString.NotNull();
            DBcontext = new DatabaseContext(ConnectionString);
            return DBcontext;
        }

        public class DatabaseContext : DbContext, IDisposable, IObjectContextAdapter, IDBContext
        {
            #region 构造函数
            /// <summary>
            /// 初始化一个 使用指定数据连接名称或连接串 的数据访问上下文类 的新实例
            /// </summary>
            /// <param name="connString">连接字串</param>
            public DatabaseContext(string connString)
                : base(new MySqlConnection(connString), true)
            {
                this.Configuration.AutoDetectChangesEnabled = false;
                this.Configuration.ValidateOnSaveEnabled = false;
                this.Configuration.LazyLoadingEnabled = false;
                this.Configuration.ProxyCreationEnabled = false;

            }
            #endregion

            #region 重载
            /// <summary>
            /// 模型创建重载
            /// </summary>
            /// <param name="modelBuilder">模型创建器</param>
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
               // System.Data.Entity.Database.SetInitializer<DatabaseContext>(null);
                OnModelCreate?.Invoke(modelBuilder);
                base.OnModelCreating(modelBuilder);
            }
            public Action<DbModelBuilder> OnModelCreate { get; set; }

            #endregion
        }
    }
}
